/**
 * ifuner 制作 @18658226071@163.com
 */

"use strict"
import ALL_ROUTER from "./ALL_PAGES"
import wxApi from "./wxApi"

const ALL_TYPE = ["navigateTo", "redirectTo", "reLaunch", "switchTab"]
const util = require("./util")

const getPageString = (routerName, queryData) => {
  if (routerName && ALL_ROUTER.hasOwnProperty(routerName)) {
    const querySting = util.objToParams(queryData)
    return `/${ALL_ROUTER[routerName]}${querySting ? `?${querySting}` : ""}`
  } else {
    console.error("pages 未定义,请在js中先定义")
    return false
  }
}
const routeTo = function(routerName, type, queryData = {}) {
  let ret = { success: false, msg: "" }
  return new Promise((resolve, reject) => {
    if (routerName && ALL_ROUTER.hasOwnProperty(routerName)) {
      if (type && ALL_TYPE.some(item => item === type)) {
        const querySting = util.objToParams(queryData)
        wxApi(type, {
          url: `/${ALL_ROUTER[routerName]}${querySting ? `?${querySting}` : ""}`
        }).then(res => {
          ret.success = true
          ret.msg = res
          resolve(ret)
        }).catch(err => {
          ret.msg = err
          reject(ret)
        })
      } else {
        ret.msg = `type不在范围值内 ${ALL_TYPE.toString()}`
        console.error(ret.msg)
        reject(ret)
      }
    } else {
      ret.msg = "routerName 不能为空"
      console.error(ret.msg)
      reject(ret)
    }
  })
}

export default {
  routes: ALL_ROUTER,
  getPageString(routerKey, query = {}) {
    return getPageString(routerKey, query)
  },
  navigateTo(routerName, data = {}) {
    return routeTo(routerName, "navigateTo", data)
  },
  redirectTo(routerName, data = {}) {
    return routeTo(routerName, "redirectTo", data)
  },
  reLaunch(routerName, data = {}) {
    return routeTo(routerName, "reLaunch", data)
  },
  switchTab(routerName, data = {}) {
    return routeTo(routerName, "switchTab", data)
  },
  navigateBack(delta = 1) {
    return wxApi("navigateBack", { delta })
  },
  target({ name, query, type }) {
    return routeTo(name, type, query)
  }
}
